import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable, Subject} from 'rxjs';

@Injectable()
export class AppWxReadyService {

  private wxReadySubject: Subject<any> = new Subject<any>();

  wxReady: Observable<any> = this.wxReadySubject.asObservable();

  constructor(private http: HttpClient) {
  }

  private get wx(): any {
    const key = 'wx';
    return window[key];
  }

  initWx() {
    this.http.get('/wx/jsconfig', {params: {url: window.location.href}})
      .subscribe((res: any) => {
        this.wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: res.appId, // 必填，公众号的唯一标识
          timestamp: res.timestamp, // 必填，生成签名的时间戳
          nonceStr: res.nonceStr, // 必填，生成签名的随机串
          signature: res.signature, // 必填，签名
          jsApiList: [
            'hideMenuItems',
            'hideAllNonBaseMenuItem'
          ] // 必填，需要使用的JS接口列表
        });
      });

    this.wx.ready(() => {
      this.wxReadySubject.next(this.wx);
      this.wxReadySubject.complete();
    });

    this.wx.error(error => {
      console.error(error.errMsg);
      this.wxReadySubject.next(null);
      this.wxReadySubject.complete();
    });

  }

}
